<?php

require_once 'Base/PostPeer.php';

/**
 * Generated Model class.
 */
class PostPeer extends Base_PostPeer
{
	protected $_source = null;
	protected $_usePostId = null;	
	public $_useSourceId = 1;
	
	public function update_posting($post_id, $user_id, $text = '', $img_vk_id = '', $wall_post_id = ''){
		$data = array(
			'is_reposted'=>1, 
			'is_deleted'=>0, 
			'user_id'=> $user_id,
			'text' => $text,
			'image_vk_id' => $img_vk_id,
			'wall_url' => $wall_post_id, 
			'reposted_at'=>date('Y-m-d H:i:s')
		);
		$this->update($data, 'id = ' . $post_id);
		ActivityPeer::getInstance()->posting($user_id, $post_id);
	}
        
        /**
         * Обновляем запись поста на то что мы его запостили
         * 
         * @param VkUser $user 
         * @param string $postId
         * @param string $text
         * @param string $imageVk
         * @param string $wallUrl
         * @throws Zend_Db_Exception 
         */
        public function updatePost($user, $postId, $text, $imageVk, $wallUrl)
        {
            $rowset = $this->findById($postId);
            if (!$rowset) {
                throw new Zend_Db_Exception("Пост $postId не найден");
            }
            
            $data = array(
                'is_reposted'=>1, 
                'is_deleted'=>0, 
                'user_id'=> $user->getId(),
                'text' => $text,
                'image_vk_id' => $imageVk,
                'wall_url' => $wallUrl, 
                'reposted_at'=>date('Y-m-d H:i:s')
            );
            $this->update($data, 'id = ' . intval($postId));
            ActivityPeer::getInstance()->posting($user, $postId);
        }
	
        /**
         * Обновляем запись поста на то что мы его удалили
         * 
         * @param int $postId
         * @param VkUser $user 
         */
	public function updateDel($postId, $user)
        {
            $rowset = $this->findById($postId);
            if (!$rowset) {
                throw new Zend_Db_Exception("Пост $postId не найден");
            }
            $data = array(
                'is_reposted'=>0,
                'is_deleted'=>1,
                'user_id'=> $user->getId(),
                'deleted_at'=>date('Y-m-d H:i:s')
            );
            $this->update($data, 'id = ' . $postId);
            ActivityPeer::getInstance()->del($user, $postId);
	}
	
	public function setSource($current_source = ''){
		$this->_source = $current_source;
		return $this;
	}
	
	public function getPost(){
            $source = Page::getInstance()->getCurrentSource();
            if(!$source){
                    throw new Exception('Key source not found');
            }

            $post = array();
            $select = $this->select()
                    ->where('source_id = ?', $source->id)
                    ->where('is_reposted = ?', 0)
                    ->where('is_deleted = ?', 0);
            if(isset($_SESSION[$source->key]['post'])){
                    $select->where('id = ?', $_SESSION[$source->key]['post']);
                    $result = $this->fetchRow($select);
                    if($result){
                        $post = $result->toArray();
                    }
            }else{
                $select->where('modified_at + INTERVAL 60 MINUTE <= NOW() or modified_at = 0');
                switch ($source->key){
                    case 'pikabu':
                        $select->order('external_rating DESC');
                        $select->limit(1);
                        $result = $this->fetchRow($select);
                        if($result){
                            $post = $result->toArray();
                        }
                        break;
                    case 'koto':
                        $result = $this->fetchAll($select)->toArray();
                        if($result){
                            $array = $result;
                            $post_rand_numb = array_rand($array, 1);
                            $post = $array[$post_rand_numb];
                        }
                        break;
                }
                if($post){
                    $this->update(array('view_count'=>$post['view_count']+1), 'id = ' . $post['id']);
                    $_SESSION[$source->key]['post'] = $post['id'];
                }
            }
            return $post;
	}
	
	public function FindId( $id ){
	
		$id = intval($id);
	
		$select = $this->select()->where('source_id = ?', $this->_useSourceId)->where('external_id = ?', $id);
	
		$result = $this->fetchRow($select);
	
		if(null !== $result){
			$this->_usePostId = $id;
			return true;
		}
	
		return false;
	
	}
	
	/**
	 * Добавление поста
	 */
	public function AddPost($data = array())
	{
		$row = $this->createRow($data);
		$row->save();
		return $row->id;
	}
	
	/**
	 * Обновляем рейтинг поста
	 */
	public function RatingUpdate($rate, $date){
	
		if(null === $this->_usePostId){
			return false;
		}
	
		$data = array(
				'external_rating'=>$rate,
				'external_created_at'=>$date
		);
	
		$this->update($data, array($this->getAdapter()->quoteInto('source_id = ?', $this->_useSourceId), $this->getAdapter()->quoteInto('external_id = ?', $this->_usePostId)));
	
	}
	
	/**
	 * Количество постов pikabu
	 */
	public function countPikabu($type)
        {
            $count = 0;
            switch($type){
                case 'untreated':
                    $select = $this->select()
                        ->where('source_id = ?', 1) // pikabu id = 1
                        ->where('is_reposted = ?', 0)
                        ->where('is_deleted = ?', 0);
                    $rows = $this->fetchAll($select);
                    if($rows){
                        $count = count($rows->toArray());
                    }
                break;
                case 'best':
                    $select = $this->select()
                        ->where('source_id = ?', 1) // pikabu id = 1
                        ->where('is_reposted = ?', 0)
                        ->where('is_deleted = ?', 0);
                    $rows = $this->fetchAll($select);
                    if($rows){
                        foreach($rows->toArray() as $row){
                            if(strpos($row['tag'], 'Лучшее') === false) continue;
                            ++$count;
                        }
                    }
                break;
            }
            return $count;
	}
	
	/**
	 * Количество постов kotomatrix
	 */
	public function countKoto(){
		$count = 0;
		$select = $this->select()
			->where('source_id = ?', 2) // koto id = 2
			->where('is_reposted = ?', 0)
			->where('is_deleted = ?', 0);
		$rows = $this->fetchAll($select);
		if($rows){
			$count = count($rows->toArray());
		}
		return $count;
	}
}

